/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.jiadakeji.ppm.modules.business.web;

import com.jiadakeji.ppm.common.beanvalidator.BeanValidators;
import com.jiadakeji.ppm.common.config.Global;
import com.jiadakeji.ppm.common.persistence.Page;
import com.jiadakeji.ppm.common.utils.IdGen;
import com.jiadakeji.ppm.common.utils.StringUtils;
import com.jiadakeji.ppm.common.utils.excel.ImportExcel;
import com.jiadakeji.ppm.common.web.BaseController;
import com.jiadakeji.ppm.modules.business.dao.BuildingDao;
import com.jiadakeji.ppm.modules.business.dao.CommunityDao;
import com.jiadakeji.ppm.modules.business.dao.RoomTypePriceDao;
import com.jiadakeji.ppm.modules.business.entity.Building;
import com.jiadakeji.ppm.modules.business.entity.Community;
import com.jiadakeji.ppm.modules.business.entity.Room;
import com.jiadakeji.ppm.modules.business.entity.RoomTypePrice;
import com.jiadakeji.ppm.modules.business.service.RoomService;
import com.jiadakeji.ppm.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 房屋Controller
 * @author HHAOYU
 * @version 2019-07-09
 */
@Controller
@RequestMapping(value = "${adminPath}/business/room")
public class RoomController extends BaseController {

	@Autowired
	private RoomService roomService;
	@Autowired
	private CommunityDao communityDao;
	@Autowired
	private BuildingDao buildingDao;
	@Autowired
	private RoomTypePriceDao roomTypePriceDao;
	
	@ModelAttribute
	public Room get(@RequestParam(required=false) String id) {
		Room entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = roomService.get(id);
		}
		if (entity == null){
			entity = new Room();
		}
		return entity;
	}
	
	@RequiresPermissions("business:room:view")
	@RequestMapping(value = {"list", ""})
	public String list(Room room, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Room> page = roomService.findPage(new Page<Room>(request, response), room); 
		model.addAttribute("page", page);
		
		UserUtils.putCache("room", room);
		return "modules/business/roomList";
	}

	@RequiresPermissions("business:room:view")
	@RequestMapping(value = "addRoomList")
	public String addRoomList(Room room, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Room> page = roomService.findPage(new Page<Room>(request, response), room);
		model.addAttribute("page", page);
		model.addAttribute("replaceId",room.getReplaceId());
		model.addAttribute("replaceName",room.getReplaceName());
		UserUtils.putCache("room", room);
		return "modules/business/roomAddList";
	}

	@ResponseBody
	@RequestMapping(value = "/getRoomList")
	public List<Room> getRoomList(Room room){
		return roomService.findList(room);
	}

	@RequiresPermissions("business:room:view")
	@RequestMapping(value = "form")
	public String form(Room room, Model model) {
		model.addAttribute("room", room);
		return "modules/business/roomForm";
	}

	@RequiresPermissions("business:room:edit")
	@RequestMapping(value = "save")
	public String save(Room room, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, room)){
			return form(room, model);
		}
		room.setBalance(null);
		roomService.save(room);
		addMessage(redirectAttributes, "保存房屋成功");
		
		redirectAttributes.addFlashAttribute("room", UserUtils.getCache("room"));
		return "redirect:"+Global.getAdminPath()+"/business/room/?repage";
	}
	
	@RequiresPermissions("business:room:edit")
	@RequestMapping(value = "delete")
	public String delete(Room room, RedirectAttributes redirectAttributes) {
		roomService.delete(room);
		addMessage(redirectAttributes, "删除房屋成功");
		
		redirectAttributes.addFlashAttribute("room", UserUtils.getCache("room"));
		return "redirect:"+Global.getAdminPath()+"/business/room/?repage";
	}


	@RequiresPermissions("business:room:edit")
	@RequestMapping(value = "import")
	public String importRoom(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletResponse response){
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			String[] names =((CommonsMultipartFile) file).getOriginalFilename().split("-");
			List<Community> communityList =null;
			Community currentCommunity ;
			if(names.length>0){
				Community community = new Community();
				community.setName(names[0]);
			communityList =	communityDao.findList(community);

			}
			if(communityList!= null){
				currentCommunity = communityList.get(0);
			}else {
				failureMsg.append("不存在该小区请先在系统中建立相同名称的小区，文件名应为 小区名+ - + 任意");
				 return "redirect:" + adminPath + "/business/room/?repage";
			}

			List<Room> list = ei.getDataList(Room.class);
			Building building = new Building();
			RoomTypePrice roomTypePrice = new RoomTypePrice();
			for (Room room : list){
				try{
					successNum++;
					if(null ==building.getCode()|| !building.getCode().equals(room.getBuildingId())){
						building.setCode(room.getBuildingId());
						building.setName(room.getBuildingId()+"栋");
						building.setCommunityId(currentCommunity.getId());
						List<Building> buildingList= buildingDao.findList(building);
						if(buildingList.isEmpty()){
							building.preInsert();
							building.setId(IdGen.uuid());
							buildingDao.insert(building);
						}else {
							building.setId(buildingList.get(0).getId());
						}

					}
					room.setBuildingId(building.getId());
					if(room.getCode().contains("-")){
						String [] codes =  room.getCode().split("-");
						room.setCode(codes[1]);
						room.setStorey(String.valueOf(Integer.valueOf(codes[1])/100));
					}
					if(room.getRoomTypePriceId() != null && !StringUtils.isBlank(room.getRoomTypePriceId())){
						roomTypePrice.setName(room.getRoomTypePriceId());
						List<RoomTypePrice> rtps= roomTypePriceDao.findList(roomTypePrice);
						if(null != rtps && !rtps.isEmpty()){
							room.setRoomTypePriceId(rtps.get(0).getId());
						}
					}
					if(room.getUseFlag() != null){
						if(room.getUseFlag().equals("是")){
							room.setUseFlag("1");
						}else {
							room.setUseFlag("0");
						}
					}
					room.setFeeAreaSize(room.getUsingAreaSize());
					roomService.save(room);
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>房屋名 "+room.getName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>房屋名 "+room.getName() +" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条数据，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条数据"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入房屋失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/business/room/?repage";
	}

}